﻿using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Tax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nop.Services.Tax
{
    public static class TaxRateExtension
    {
        public static List<Surcharge> ToSurcharges(this IList<TaxSurcharge> taxRates, Order order, OrderProductVariant orderProductVariant)
        {
            return taxRates.Select(x => new Surcharge()
            {
                OrderId = order == null ? 0 : order.Id,
                OrderProductVariantId = orderProductVariant == null ? 0 : orderProductVariant.Id,
                PercentageOrFee = x.PercentageOrFee,
                StateProvinceId = x.StateProvinceId,
                SurchargeTypeId = x.SurchargeTypeId,
                Value = x.Value,
                Zip = x.Zip
            }).ToList();
        }

        public static List<Surcharge> ToSurcharges(this IList<TaxSurcharge> taxRates)
        {
            return ToSurcharges(taxRates, null, null);
        }

        public static List<TaxSurcharge> ToTaxes(this IList<Surcharge> surcharges)
        {
            return surcharges.Select(x => new TaxSurcharge()
            {
                PercentageOrFee = x.PercentageOrFee,
                StateProvinceId = x.StateProvinceId ?? 0,
                SurchargeTypeId = x.SurchargeTypeId,
                Value = x.Value,
                Zip = x.Zip
            }).ToList();
        }

        public static List<TaxSurcharge> ToDistinctTypes(this IList<TaxSurcharge> taxRates)
        {
            var newTaxRates = new List<TaxSurcharge>();

            foreach (var item in taxRates)
            {
                var rate = newTaxRates.SingleOrDefault(x =>
                    x.StateProvinceId == item.StateProvinceId &&
                    x.CountryId == item.CountryId &&
                    x.Zip == item.Zip &&
                    x.SurchargeTypeId == item.SurchargeTypeId &&
                    x.PercentageOrFee == item.PercentageOrFee);
                if (rate != null)
                {
                    rate.Value += item.Value;
                }
                else
                {
                    newTaxRates.Add(item);
                }
            }
            return newTaxRates;
        }
    }
}
